package com.kudian.common.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import org.apache.log4j.Logger;

/**
 * Created by apple on 16/7/16.
 */
public class MessageUtils {
    private static final Logger logger = Logger.getLogger(MessageUtils.class);

    private static final String appKey ="9200847a7a4787ed6b7e0c61";
    private static final String masterSecret = "bc28a4499ab81e5b6126e2f9";

    public static void sendmsg2bus(String msg, String SRegistrationId) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        try {
            PushPayload payload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.registrationId(SRegistrationId))
                    .setMessage(Message.newBuilder()
                            .setMsgContent(msg)
                            .addExtra("from", "JPush")
                            .build())
                    .build();

            PushResult result = jpushClient.sendPush(payload);
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);

        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
        }
    }
}
